'use strict';
const dbHelper = require("db-helper");
const db = uniCloud.database();
const dbCmd = db.command;
const {wxPubConfig} = require("config")
const WxPubApi = require("wx-public-api");
const wxPubApi = new WxPubApi();
const token = "dskj88";
const crypto = require('crypto');
const xml2js = require('xml2js');
const xmlParser = new xml2js.Parser({explicitArray: false, ignoreAttrs: true, explicitRoot: false});
const msg = "HI，欢迎来到第三空间长沙站，点击下列门店菜单，了解各门店最新优惠活动政策\n\r"

const city = "4301"

const getMenus = async () => {
	let res = await db.collection("t3ds-store-shortcut-menu").aggregate()
		.lookup({
			from: "t3ds-store",
			localField: "storeId",
			foreignField: "_id",
			as: "store"
		})
		.match({
			'store.region.city.value': city
		})
		.limit(7)
		.project({
			title: 1,
			goodsId: 1,
			skuId: 1,
			shareManId: 1
		})
		.end()
	return res.data
}

exports.main = async (event, context) => {
	//event为客户端上传的参数
	let startTime = Date.now();
	console.log('收到公众号事件 : ', event)
	let {queryStringParameters, body} = event;
	if (queryStringParameters) {
		let {echostr, nonce, signature, timestamp} = queryStringParameters;
		if (!nonce || !signature || !timestamp) {
			console.error("参数错误");
			return {
				code: 500,
				msg: '参数错误'
			}
		}
		let a = [token, timestamp, nonce];
		a.sort();
		let s = a.join('');
		let t = crypto.createHash("sha1").update(s).digest("hex");
		if (t !== signature) {
			console.error("签名验证失败");
			return {
				code: 500,
				msg: "签名校验失败"
			};
		} else if (echostr) {
			console.log("直接返回echostr");
			return echostr;
		}
		if (!body) {
			return "";
		}
		body = new Buffer(body , 'base64').toString();
		console.log("body base64解码后", body);
		let data = await new Promise((resolve, reject) => {
			xmlParser.parseString(body, (err, res) => {
				if (err) {
					console.error(`无法解析body"${body}"`, err);
					resolve();
				} else {
					resolve(res);
				}
			})
		})
		if (!data) {
			return "";
		}
		console.log("转换后的body", data);
		if (data.MsgType !== "event") {
			return "";
		}
		try{
			let storeMenus, storeId;
			if (data.Event === "unsubscribe") {
				await db.collection("t3ds-wx-pub-user").where({
					openId: data.FromUserName,
					city: city
				}).remove();
				return '';
			} else if (data.Event === "subscribe") {
				var userData = await dbHelper.getOne("t3ds-wx-pub-user", {
					openId: data.FromUserName,
					city: city
				});
				if (!userData) {
					let userInfo = await wxPubApi.getUserInfo(city, data.FromUserName);
					userData = {
						openId: data.FromUserName,
						unionId: userInfo.unionid,
						detail: userInfo,
						city: city,
						createTime: Date.now()
					}
					await dbHelper.insert("t3ds-wx-pub-user", userData);
					console.log("用户保存成功");
				}
				storeMenus = await getMenus()
				if (data.EventKey) {
					let matches = data.EventKey.match(/\d/);
					if (matches && matches.length) {
						let storeId = matches[0] + '';
						let menu = await dbHelper.getOne("t3ds-store-shortcut-menu", {
							storeId: storeId
						});
						if (menu) {
							if (storeMenus[0].storeId != menu.storeId) {
								var idx = -1;
								for (var i = 0; i < storeMenus.length; i++) {
									if (storeMenus[i].storeId == menu.storeId) {
										idx = i;
										break;
									}
								}
								if (idx != -1) {
									storeMenus.splice(idx, 1);
									storeMenus.unshift(menu);
								}
							}
						}
					}
				}
			} else if (data.Event === "SCAN") {
				storeMenus = await getMenus()
				if (data.EventKey) {
					let menu = await dbHelper.getOne("t3ds-store-shortcut-menu", {
						storeId: data.EventKey + ''
					});
					console.log("menu", menu);
					if (menu) {
						if (storeMenus[0].storeId != menu.storeId) {
							var idx = -1;
							for (var i = 0; i < storeMenus.length; i++) {
								if (storeMenus[i].storeId == menu.storeId) {
									idx = i;
									break;
								}
							}
							if (idx != -1) {
								storeMenus.splice(idx, 1);
								storeMenus.unshift(menu);
							}
						}
					}
				}
			} else {
				return '';
			}
			var message = msg;
			var i = 0;
			storeMenus.forEach(item => {
				let params = []
				if (item.goodsId) {
					params.push(`goodsId=${item.goodsId}`)
				}
				if (item.skuId) {
					params.push(`skuId=${item.skuId}`)
				}
				if (item.shareManId) {
					params.push(`shareManId=${item.shareManId}`)
				}
				let query = params.join('&')
				message += `<a data-miniprogram-appid="wx609a0a547e98415d" data-miniprogram-path="pagesGroup/platform/goods-detail?${query}">${item.title || ''}</a>\n\r`
			})
			let endTime = Date.now()
			let cost = endTime - startTime;
			console.log("耗时：", `${cost / 1000}`);
			return `<xml>
					  <ToUserName><![CDATA[${data.FromUserName}]]></ToUserName>
					  <FromUserName><![CDATA[${data.ToUserName}]]></FromUserName>
					  <CreateTime>${Date.now()}</CreateTime>
					  <MsgType><![CDATA[text]]></MsgType>
					  <Content><![CDATA[${message}]]></Content>
					</xml>`;
		} catch(e){
			console.error("解析公众号事件遇到错误", e);
		}
	} else {
		return {
			code: 500,
			msg: "无权限"
		}
	}
};
